﻿using System.Collections.Generic;
using UnityEngine;

namespace XUDocking
{
    public class XUDockingCallback : MonoBehaviour
    {
        private static XUDockingCallback instance;
        public static XUDockingCallback GetInstance()
        {
            if (instance == null)
            {
                instance = new GameObject("XUDockingCallback").AddComponent<XUDockingCallback>();
                DontDestroyOnLoad(instance.gameObject);
            }
            return instance;
        }

        private Dictionary<ReceiveOpt, List<EVENT_JSON>> listeners = new Dictionary<ReceiveOpt, List<EVENT_JSON>>();

        public void AddListener(ReceiveOpt opt, EVENT_JSON e)
        {
            if (!listeners.ContainsKey(opt))
            {
                listeners.Add(opt, new List<EVENT_JSON>() { e });
            }
            else
            {
                if (!listeners[opt].Contains(e))
                {
                    listeners[opt].Add(e);
                }
            }
        }

        public void RemoveListener(ReceiveOpt opt, EVENT_JSON e)
        {
            if (listeners.ContainsKey(opt))
            {
                if (listeners[opt].Contains(e))
                {
                    listeners[opt].Remove(e);
                }
            }
        }

        public void ReceiveMessage(string json)
        {
            XUDockingDataReceive dataReceive = JsonUtility.FromJson<XUDockingDataReceive>(json);
            if (dataReceive != null)
            {
                if (listeners.ContainsKey(dataReceive.opt))
                {
                    foreach (var listener in listeners[dataReceive.opt])
                    {
                        if (listener != null)
                        {
                            listener.Invoke(dataReceive.json);
                        }
                    }
                }
            }
            else
            {
                Debug.LogError("ReceiveMessage Error , json = " + json);
            }
        }
    }
}
